﻿using BusinessLayer;
using BusinessLayer.DatabaseEntities;
using BusinessLayer.VDataEntities;
using CustomerServiceCenter.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using CustomerServiceCenter.Helper;
using System.IO;
using System.Threading;

namespace CustomerServiceCenter.Controllers.API
{
    public class SettingsController : ApiController
    {
        //根据setting页面的查询条件获取工程师的信息
        public List<SettingsModel> OperatorInfo(selectModel model)
        {
            List<VOperator> list = ProjectBusiness.GetOperatorInfoByName(model.MemberName);
            //List<VOperator> list = TicketBusiness.GetOperatorInfo(model.MemberID);
            List<SettingsModel> settingsList = new List<SettingsModel>();
            //判断查询条件是否包含项目

            foreach (var item in list)
            {
                SettingsModel settings = new SettingsModel();
                settings.OperatorID = item.ID;
                settings.UserName = item.Name;
                settingsList.Add(settings);
            }
            return settingsList;
        }

        [HttpPost]
        public List<SettingsModel> ApplicationInfoByOperator(selectModel model)
        {
            long[] applicationID = ProjectBusiness.GetApplicationIDOrOperatorID(model.MemberID);
            List<SettingsModel> settingsList = new List<SettingsModel>();
            if (null != applicationID && applicationID.Length > 0)
            {
                List<VApplication> list = ProjectBusiness.GetApplicationInfoById(applicationID);
                foreach (var item in list)
                {
                    SettingsModel settings = new SettingsModel();
                    settings.Project = item.Name;
                    settings.ProjectID = item.ID;
                    settingsList.Add(settings);
                }
            }
            return settingsList;
        }




        /// <summary>
        /// 获取工程师的信息
        /// </summary>
        /// <param name="OperatorID"></param>
        /// <returns></returns>
        public List<OperatorInfo> GetOperatorInfo(int OperatorID)
        {
            List<OperatorInfo> operatorList = new List<OperatorInfo>();
            List<VOperator> list = TicketBusiness.GetOperatorInfo(OperatorID);
            foreach (var item in list)
            {
                OperatorInfo operatorInfo = new OperatorInfo();
                operatorInfo.UserName = item.Name;
                operatorInfo.Mobile = item.Mobile;
                operatorInfo.TelePhone = item.Telephone;
                operatorInfo.Email = item.Email;
                operatorInfo.Password = item.PassWord;
                operatorInfo.Status = item.IsActive;
                operatorList.Add(operatorInfo);
            }
            return operatorList;
        }


        /// <summary>
        /// 修稿工程师的信息
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public string ModifyOperatorInfoAndMap(OperatorInfo info)
        {
            string message = "";
            try
            {
                long[] mapInfo = ProjectBusiness.GetApplicationIDOrOperatorID(info.OperatorID, null);
                ProjectBusiness.ModifyOperatorInfo(info.OperatorID, true, info.Mobile, info.Email, info.TelePhone);
                if (null != info.AllProjectID && info.AllProjectID.Length > 0)
                {
                    for (int i = 0; i < info.AllProjectID.Length; i++)
                    {
                        //如果原有的不包含现在的projectID，那么久添加这个project 
                        if (!mapInfo.Contains(info.AllProjectID[i]))
                        {
                            ProjectBusiness.AddOperatorAndApplicationMap(info.OperatorID, info.AllProjectID[i], true);
                            message = "success";
                        }
                        else
                        {
                            //如果包含，则将包含的项目设置为true
                            ProjectBusiness.ModifyOperatorAndApplicationMap(info.OperatorID, info.AllProjectID[i], true);
                            message = "success";
                        }
                    }
                    for (int i = 0; i < mapInfo.Length; i++)
                    {
                        //如果现在的PROJECTID不包含原有的projectID那么就将不包含的projectID设置为FALSE

                        if (!info.AllProjectID.Contains(mapInfo[i]))
                        {
                            ProjectBusiness.ModifyOperatorAndApplicationMap(info.OperatorID, mapInfo[i], false);
                            message = "success";
                        }
                    }
                }
                else
                {
                    for (int j = 0; j < mapInfo.Length; j++)
                    {
                        //如果为空，则将所有的project设置为FALSE
                        ProjectBusiness.ModifyOperatorAndApplicationMap(info.OperatorID, mapInfo[j], false);
                        message = "success";
                    }
                }
            }
            catch (Exception)
            {
                message = "ModifyError";
            }
            return message;
        }

        public string ModifyOperatorStatus(DisableModel model)
        {
            string message = "";
            try
            {
                if (model.ID == 0)
                {
                    return "操作员不能为空";
                }
                long[] ID = new long[] { model.ID };
                List<VOperator> operatorInfo = ProjectBusiness.GetOperatorInfoById(ID);
                if (null != operatorInfo && operatorInfo.Count > 0)
                {
                    if (operatorInfo[0].RoleID == 1)
                    {
                        return "不可修改管理员状态";
                    }
                }
                ProjectBusiness.ModifyOperatorInfo(model.ID, model.Status);
                ProjectBusiness.ModifyOperatorAndApplicationMap(model.ID, 0, model.Status);
                message = "success";
            }
            catch (Exception)
            {
                message = "OperatorDisableError";
                // throw;
            }
            return message;

        }

        public string ModifyApplicationStatus(DisableModel model)
        {
            string message = "";
            try
            {
                if (model.ID == 0)
                {
                    return "项目不能为空";
                }
                long[] ID = new long[] { model.ID };
                long[] IssueTypeID = new long[1];
                ProjectBusiness.modifyApplicationStatus(ID, model.Status);
                List<IssueType> list = ProjectBusiness.GetIssueType(ID);
                if (null != list && list.Count > 0)
                {
                    ProjectBusiness.ModifyIssueTypeStatus(IssueTypeID, ID, model.Status);
                }
                message = "success";
            }
            catch (Exception)
            {
                message = "DisableError";
                // throw;
            }
            return message;

        }

        public string ModifyClientStatus(DisableModel model)
        {
            string message = "";
            try
            {
                if (model.ID == 0)
                {
                    return "项目不能为空";
                }
                ProjectBusiness.modifyClientStatus(model.ID, model.Status);
                long[] ProjrctID = ProjectBusiness.GetApplicationIDByClientID(model.ID);
                if (ProjrctID.Length > 0 && null != ProjrctID)
                {
                    ProjectBusiness.modifyApplicationStatus(ProjrctID, model.Status);
                }
                message = "success";
            }
            catch (Exception)
            {
                message = "DisableError";
                // throw;
            }
            return message;
        }



        //获取所有公司的信息
        public List<VClient> GetClientInfo(string ClientName)
        {
            List<VClient> clientList = ProjectBusiness.GetClientInfo(ClientName);
            return clientList;
        }

        /// <summary>
        /// 添加项目
        /// </summary>
        /// <param name="projectName"></param>
        /// <param name="clientID"></param>
        [HttpPost]
        public string AddProject(AddModel model)
        {
            string message = "";
            string errorMsg = "不能为空或空格";
            try
            {
                if (model.ProjectName == null)
                {
                    return "ProjectName" + errorMsg;
                }
                if (model.ClientID == 0)
                {
                    return "Client" + errorMsg;
                }
                List<VApplication> projectInfo = ProjectBusiness.GetApplicationInfo(0, model.ClientID, model.ProjectName, null);
                if (null != projectInfo && projectInfo.Count > 0)
                {
                    if (projectInfo[0].IsActive)
                    {
                        return "Project already exist";
                    }
                    ProjectBusiness.modifyApplicationStatusBySome(true, model.ProjectName, model.ClientID);
                    message = "success";
                }
                else
                {
                    ProjectBusiness.AddProject(model.ProjectName, model.ClientID, model.IsWeChatActive,model.OnCall);
                    message = "success";
                }

            }
            catch (Exception)
            {
                message = "addError";
                //throw;
            }
            return message;
        }

        /// <summary>
        /// 添加客户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public string AddClient()
        {
            HttpRequest request = HttpContext.Current.Request;
            string ClientName = request.Params["clientName"];
            string CropID = request.Params["CropID"];
            string Secret = request.Params["Secret"];
            string APPID = request.Params["AppID"];
            string Guuid = request.Params["Guuid"];
            string errorMsg = "不能为空或空格";
            #region 空值判断
            if (ClientName == null || ClientName.Trim().Length <= 0)
            {
                return "ClientName" + errorMsg;
            }
            else
            {
               List<VClient> clientInfo = ProjectBusiness.GetClientInfo(ClientName);
               if (null != clientInfo && clientInfo.Count > 0)
               {
                   return "Client already exist";
               }
            }
            if (CropID == null || CropID.Trim().Length <= 0)
            {
                return "CropID" + errorMsg;
            }
            if (Secret == null || Secret.Trim().Length <= 0)
            {
                return "Secret" + errorMsg;
            }
            if (APPID == null || APPID.Trim().Length <= 0)
            {
                return "APPID" + errorMsg;
            }
            if (Guuid == null || Guuid.Trim().Length <= 0)
            {
                return "Guuid" + errorMsg;
            }
            #endregion
            //添加信息
            VClientEntity client = new VClientEntity
        {
            ClientName = ClientName,
            CropID = CropID,
            Secret = Secret,
            APPID = APPID,
            Guuid = Guuid
        };
            long clientId;
            try
            {
                clientId = ClientBusiness.AddClient(client);
            }
            catch (Exception)
            {
                return "Add client Error";
                throw;
            }

            if (request.Files.Count > 0)
            {
                HttpPostedFile file = request.Files[0];
                System.Drawing.Image img = System.Drawing.Image.FromStream(file.InputStream);
                string fileName = clientId + ".jpg";
                string mapPath = System.Web.Hosting.HostingEnvironment.MapPath("~/content/wechat/logo");
                if (!Directory.Exists(mapPath))
                {
                    Directory.CreateDirectory(mapPath);
                }
                bool flag = WeChatController.GetPicThumbnail(img, mapPath + "/" + fileName, 50);
                if (!flag)
                {
                    return "没法保存logo";
                }
            }
            return "success";
            //保存图标
        }

        public string AddOperator(OperatorInfo model)
        {
            string message = "";
            string errorMsg = "不能为空或空格";
            try
            {
                if (model.UserName == null)
                {
                    return "UserName" + errorMsg;
                }
                if (model.Mobile == null)
                {
                    return "Mobile" + errorMsg;
                }
                if (model.Email == null)
                {
                    return "Email" + errorMsg;
                }
                if (model.TelePhone == null)
                {
                    return "TelePhone" + errorMsg;
                }
                List<VOperator> operatorList = ProjectBusiness.GetOperatorInfoByName();
                bool flag = true;
                foreach (var item in operatorList)
                {
                    if (item.Name.Trim().Equals(model.UserName.Trim()))
                    {
                        flag = false;
                        break;
                    }
                }
                if (flag)
                {
                    Random rd = new Random();
                    int num = rd.Next(100000, 1000000);
                    string info = "您的登录密码为" + num + ",请尽早登录系统，并修改新的密码";
                    EmailInfo infomation = new EmailInfo { toEmailAddress = model.Email.Trim(), info = info };
                    CEmail.sendEmailFunction(infomation);
                    long operatorID = ProjectBusiness.AddOperator(model.UserName, model.Mobile, model.Email, model.TelePhone, num.ToString(), 2);
                    if (null != model.AllProjectID && model.AllProjectID.Length > 0)
                    {
                        for (int i = 0; i < model.AllProjectID.Length; i++)
                        {
                            ProjectBusiness.AddOperatorAndApplicationMap(operatorID, model.AllProjectID[i], true);
                        }
                    }
                    //message = CEmail.PCEmailReturnMassage;
                    message = "success";
                }
                else
                {
                    message = "UserName already exist";
                }
            }
            catch (Exception)
            {
                message = "addError";
                //throw;
            }
            return message;
        }

        /// <summary>
        /// 通过名字获取项目的信息
        /// </summary>
        /// <param name="Name"></param>
        /// <returns></returns>
        public List<VApplication> GetApplicationInfo(string ProjectName)
        {
            List<VApplication> list = ProjectBusiness.GetApplicationInfo(0, 0, ProjectName);
            return list;
        }

        public List<IssueTypePCModel> GetIssueTypeInfos(long ProjectID)
        {
            List<IssueTypePCModel> IssueTypeList = new List<IssueTypePCModel>();
            if (ProjectID == 0)
            {
                List<IssueType> list = ProjectBusiness.GetIssueTypeInfoBySome(0, null);
                foreach (var item in list)
                {
                    bool flag = true;
                    foreach (var item2 in IssueTypeList)
                    {
                        if (item.IssueTypeDescription.Trim().Equals(item2.IssueTypeDescription.Trim()))
                        {
                            flag = false;
                            break;
                        }
                    }
                    if (flag)
                    {
                        IssueTypePCModel IssueModel = new IssueTypePCModel();
                        IssueModel.ApplicationID = item.ApplicationID;
                        IssueModel.ID = item.ID;
                        IssueModel.IssueTypeDescription = item.IssueTypeDescription;
                        IssueModel.IsActive = item.IsActive;
                        IssueModel.Type = item.Type;
                        IssueTypeList.Add(IssueModel);
                    }
                }
            }
            else
            {
                long[] ID = new long[] { ProjectID };
                List<IssueType> list = ProjectBusiness.GetIssueType(ID);
                foreach (var item in list)
                {
                    IssueTypePCModel IssueModel = new IssueTypePCModel();
                    IssueModel.ApplicationID = item.ApplicationID;
                    IssueModel.ID = item.ID;
                    IssueModel.IssueTypeDescription = item.IssueTypeDescription;
                    IssueModel.IsActive = item.IsActive;
                    IssueModel.Type = item.Type;
                    IssueTypeList.Add(IssueModel);
                }
            }
            return IssueTypeList;
        }

        #region 修改IssueType关系的信息
        //------------------------------------------------------------------------------------------------------------------------
        /// <summary>
        /// 修稿IssueType关系的信息
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public string ModifyIssueTypeAndMap(IssueTypeMapModel info)
        {
            string message = "IssueTypeModifyError";
            try
            {
                long[] applicationID = new long[] { info.ApplicationID };
                if (null != info.IsWeChatActive)
                {
                    ProjectBusiness.modifyApplicationStatus(applicationID, true, info.IsWeChatActive);
                    message = "success";
                }
                //根据页面上传过来的applicationid来查找issuetype信息
                List<IssueType> IssueTypeInfoList = ProjectBusiness.GetIssueType(applicationID, null);
                if (null != info.NewIssueType && null != info.Type)
                {
                    bool flag = true;
                    foreach (var item in IssueTypeInfoList)
                    {
                        if (info.NewIssueType.Trim().Equals(item.IssueTypeDescription.Trim()))
                        {
                            //数据库中存在的状态为false的改成true                           
                            long[] IssueTypeID = new long[] { item.ID };
                            ProjectBusiness.ModifyIssueTypeStatus(IssueTypeID, applicationID, true);
                            message = "success";
                            flag = false;
                            break;
                        }
                    }
                    if (flag)
                    {
                        ProjectBusiness.AddNewIssueType(info.NewIssueType, info.ApplicationID, true, info.Type);
                        message = "success";
                    }
                }
                if (null == info.IssueTypeID || info.IssueTypeID.Length < 0)
                {
                    for (int j = 0; j < IssueTypeInfoList.Count; j++)
                    {
                        //如果为空，则将所有的IssueType设置为FALSE
                        long[] IssueTypeID = new long[] { IssueTypeInfoList[j].ID };
                        ProjectBusiness.ModifyIssueTypeStatus(IssueTypeID, applicationID, false);
                        message = "success";
                    }
                }
                else
                {
                    for (int i = 0; i < IssueTypeInfoList.Count; i++)
                    {
                        //如果现在的IssueType不包含原有的IssueType那么就将不包含的IssueType设置为FALSE
                        if (!info.IssueTypeID.Contains(IssueTypeInfoList[i].ID) && IssueTypeInfoList[i].IsActive == true)
                        {
                            long[] IssueTypeID = new long[] { IssueTypeInfoList[i].ID };
                            ProjectBusiness.ModifyIssueTypeStatus(IssueTypeID, applicationID, false);
                            message = "success";
                        }
                    }
                }
            }
            catch (Exception)
            {
                message = "IssueTypeModifyError";
            }
            return message;
        }
        #endregion

        public string ResetPassWord(DisableModel model)
        {

            try
            {
                if (model.ID == 0)
                {
                    return "请确定要重置的操作员";
                }
                Random rd = new Random();
                int num = rd.Next(100000, 1000000);
                long[] ID = new long[] { model.ID };
                string info = "您的密码已重置，重置后的密码为" + num + ",请尽早登录系统，并修改新的密码";
                List<VOperator> operatorInfo = ProjectBusiness.GetOperatorInfoById(ID);
                if (null != operatorInfo && operatorInfo.Count > 0)
                {
                    EmailInfo infomation = new EmailInfo { toEmailAddress = operatorInfo[0].Email.Trim(), info = info };
                    CEmail.sendEmailFunction(infomation);
                }
                AdminBusiness.ResetPassword(model.ID, num.ToString());
                string message = CEmail.PCEmailReturnMassage;
                return "密码重置成功" + message;
            }
            catch (Exception)
            {
                return "密码重置失败";
                //throw;
            }
        }

        public string GetEmailMessage()
        {
            return CEmail.PCEmailReturnMassage;
        }

    }
}
